using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;

using System.Text;
using System.Text.RegularExpressions;
using System.IO;

using System.Data;
using System.Data.OleDb;

using System.ComponentModel;


namespace GURUCORE.Lib.Core.Text
{
    public static class TextHelper
    {
        #region CHECK VALIDATE DATA
        
        /// <summary>
        /// return true if correct data, return false if incorrect
        /// </summary>
        /// <param name="pstrNumber"></param>
        /// <returns></returns>
        public static bool IsNumeric(string pstrNumber)
        {
            try
            {
                double dblResult = 0;
                return Double.TryParse(pstrNumber, System.Globalization.NumberStyles.Any,
                    System.Globalization.NumberFormatInfo.CurrentInfo, out dblResult);
            }
            catch
            {
                return false;
            }
        }
        
        /// <summary>
        /// return true if correct data, return false if incorrect 
        /// </summary>
        /// <param name="pstrNumber"></param>
        /// <returns></returns>
        public static bool IsPositiveNumeric(string pstrNumber)
        {
            try
            {
                decimal decResult = 0;
                decResult = decimal.Parse(pstrNumber);
                if (decResult <= 0)
                {
                    return false;
                }
                else
                {
                    return true;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// Validate percent number between 0 and 100
        /// </summary>
        /// <param name="pstrNumber">Number of percent to be validated</param>
        /// <returns>boolean</returns>
        public static bool IsValidPercent(string pstrNumber)
        {
            try
            {
                if (IsPositiveNumeric(pstrNumber))
                {
                    double dblNumber = 0;
                    if (Double.TryParse(pstrNumber, System.Globalization.NumberStyles.Any,
                                        System.Globalization.NumberFormatInfo.CurrentInfo, out dblNumber))
                    {
                        if ((dblNumber > 0) && (dblNumber <= 100))
                        {
                            return true;
                        }
                        else
                        {
                            return false;
                        }
                    }
                    else
                    {
                        return false;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }
               
        /// <summary>
        /// Check input string is Phone/Fax number or not
        /// return true if correct data, return false if incorrect
        /// </summary>
        /// <param name="pstrNumber"></param>
        /// <returns></returns>
        public static bool IsPhoneFaxNumber(string pstrNumber)
        {
            // return true if pstrNumber is valid Phone/Fax number
            return !Regex.IsMatch(pstrNumber, "[a-zA-Z]");
        }
                        
        /// <summary>
        /// Check input string is valid email address
        /// Return true if pstrEmail is in valid e-mail format.
        /// </summary>
        /// <param name="pstrEmail"></param>
        /// <returns></returns>
        public static bool IsValidEmail(string pstrEmail)
        {
            // Return true if pstrEmail is in valid e-mail format.
            return Regex.IsMatch(pstrEmail, @"^([\w-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([\w-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$");
        }


        public static bool IsNameValueString(string p_s)
        {
            // p_s is matched with string like   a=b;c=d;
            return Regex.IsMatch(p_s, "(.+?=.+?;)+?$");            
        }

        #endregion

        #region Thachnn: Find And Replace Pattern with Regular Expression

        /// <summary>
        /// Thachnn: Find and replace all in the provided string
        /// using Regular Expression syntax to find and replace
        /// <author>Thachnn: 12/01/2006</author>		
        /// </summary>		
        /// <example></example>		
        /// <remarks></remarks>				
        /// <value></value>		
        /// <param name="pstrWhereToFind"></param>
        /// <param name="pstrFindWhatPattern"></param>
        /// <param name="pstrReplaceWithPattern"></param>
        /// <param name="pRegExOption"></param>				
        /// <returns></returns>				
        public static string FindAndReplaceAll(string pstrWhereToFind, string pstrFindWhatPattern, string pstrReplaceWithPattern, RegexOptions pRegExOption)
        {
            return Regex.Replace(pstrWhereToFind, pstrFindWhatPattern, pstrReplaceWithPattern, pRegExOption);
        }

        /// <summary>
        /// Thachnn: Find and replace all in the provided string
        /// using Regular Expression syntax to find and replace
        /// Process with no option of Regular Expression Engine
        /// <author>Thachnn: 12/01/2006</author>
        /// </summary>
        /// <param name="pstrWhereToFind"></param>
        /// <param name="pstrFindWhatPattern"></param>
        /// <param name="pstrReplaceWithPattern"></param>
        /// <returns></returns>
        public static string FindAndReplaceAll(string pstrWhereToFind, string pstrFindWhatPattern, string pstrReplaceWithPattern)
        {
            return FindAndReplaceAll(pstrWhereToFind, pstrFindWhatPattern, pstrReplaceWithPattern, RegexOptions.None);
        }


        /// <summary>
        /// Wrapper of FindAndReplaceAll() function - for short function calling
        // Thachnn: Find and replace all in the provided string
        /// using Regular Expression syntax to find and replace
        /// <author>Thachnn: 12/01/2006</author>
        /// </summary>		
        /// <example></example>		
        /// <remarks></remarks>				
        /// <value></value>		
        /// <param name="pstrWhereToFind"></param>
        /// <param name="pstrFindWhatPattern"></param>
        /// <param name="pstrReplaceWithPattern"></param>
        /// <param name="pRegExOption"></param>				
        /// <returns></returns>				
        public static string FARA(string pstrWhereToFind, string pstrFindWhatPattern, string pstrReplaceWithPattern, RegexOptions pRegExOption)
        {
            return FindAndReplaceAll(pstrWhereToFind, pstrFindWhatPattern, pstrReplaceWithPattern, pRegExOption);
        }

        /// <summary>
        /// Wrapper of FindAndReplaceAll() function - for short function calling
        /// Thachnn: Find and replace all in the provided string
        /// using Regular Expression syntax to find and replace
        /// Process with no option of Regular Expression Engine
        /// <author>Thachnn: 12/01/2006</author>		
        /// </summary>
        /// <param name="pstrWhereToFind"></param>
        /// <param name="pstrFindWhatPattern"></param>
        /// <param name="pstrReplaceWithPattern"></param>
        /// <returns></returns> 
        public static string FARA(string pstrWhereToFind, string pstrFindWhatPattern, string pstrReplaceWithPattern)
        {
            return FindAndReplaceAll(pstrWhereToFind, pstrFindWhatPattern, pstrReplaceWithPattern, RegexOptions.None);
        }



        #endregion Thachnn: Find And Replace Pattern	with Regular Expression

		public static string HtmlDeTag(string p_sHtml)
		{
			Regex regex = new Regex("<[^>]+>");
			return regex.Replace(p_sHtml, string.Empty);
		}

		public static string ProcessUtf8Escape(string p_sSource)
		{
			int nLength = p_sSource.Length;
			string sDest = string.Empty;
			int nStart = 0;
			int nEnd = 0;
			int nSemiColonIdx = -1;
			while (nStart < nLength)
			{
				nEnd = p_sSource.IndexOf("&#", nStart);
				if (nEnd < 0)
				{
					nEnd = nLength;
				}
				sDest = sDest + p_sSource.Substring(nStart, nEnd - nStart);

				try
				{
					nSemiColonIdx = p_sSource.IndexOf(';', nEnd + 2);
				}
				catch
				{
					nSemiColonIdx = -1;
				}
				if (nSemiColonIdx >= 0)
				{
					string sCode = p_sSource.Substring(nEnd + 2, nSemiColonIdx - nEnd - 2);
					try
					{
						Int16 nCode = Convert.ToInt16(sCode);
						sDest = sDest + (char)nCode;
						nStart = nEnd + sCode.Length + 3;
					}
					catch
					{
						nStart = nEnd + 1;
					}
				}
				else
				{
					nStart = nEnd + 1;
				}
			}
			return sDest;
		}


        /// <summary>
        /// G: parse the namevalue string (in format a=b;c=d;e=3) into hashtable
        /// </summary>
        /// <param name="p_sNameValStr">(in format a=b;c=d;e=3)</param>
        /// <returns>empty if error</returns>
        public static Hashtable ParseNameValueString(string p_sNameValStr)
        {
            return ParseNameValueString(p_sNameValStr, ';','=');
        }

        /// <summary>
        /// G: parse the namevalue string into hashtable. string contain several pair, each pair is namevalue.
        /// </summary>
        /// <param name="p_sNameValStr">input string to parse</param>
        /// <param name="p_cPairSeperator">common = ;</param>
        /// <param name="p_cKeyValueSeperator">common = =</param>
        /// <returns>empty if error</returns>
        public static Hashtable ParseNameValueString(string p_sNameValStr, char p_cPairSeperator, char p_cKeyValueSeperator)
        {
            Hashtable htPair = new Hashtable();
            if (string.IsNullOrEmpty(p_sNameValStr)) // PERFORMANCE: short circuit
            {
                return htPair;
            }

            char[] arrPairSeperator = { p_cPairSeperator };
            string[] arrPair = p_sNameValStr.Split(arrPairSeperator, StringSplitOptions.RemoveEmptyEntries);

            foreach (string sPair in arrPair)
            {
                string[] arrValue = sPair.Split(p_cKeyValueSeperator);
                string sName = arrValue[0].Trim();
                string sValue = arrValue[1].Trim();

                htPair.Add(sName, sValue);
            }
            return htPair;            
        }


		#region Thachnn File, Time function

        const string UTC_STRING_FORMAT = "yyyyMMddHHmmss";




        /// <summary>
        /// Thachnn: 25/Sep/2005
        /// Get IP address and subnet mask of the current PCS-running machine
        /// </summary>
        /// <returns>string, contain ipaddress@subnetmass. Ex: 192.168.1.1:255.255.255.0</returns>
        //		public static string GetLocalMachineIPAddress()
        //		{
        //			string ret = "";
        //			ManagementObjectSearcher query = new ManagementObjectSearcher("SELECT *	FROM Win32_NetworkAdapterConfiguration") ;
        //			ManagementObjectCollection queryCollection = query.Get();
        //			foreach( ManagementObject mobject in queryCollection )
        //			{
        //				if((bool)mobject["IPEnabled"] == true)
        //				{
        //					string[] addresses = (string[])mobject["IPAddress"];
        //					string[] subnets = (string[])mobject["IPSubnet"];
        //					foreach(string s in addresses)
        //					{
        //						ret += s ;
        //					}
        //					foreach(string s in subnets)
        //					{
        //						ret += "@" + s;
        //					}
        //				}
        //			}
        //			//DEBUG:
        //			string ret = "192.168.1.199@255.255.255.0";
        //			return ret;
        //		}



        /// <summary>		
        /// Thachnn: 24/Sep/2005
        /// Get current date time, convert to UTC string. Format = yyyyMMddHHmmss
        /// Ex: 20050916590000
        /// </summary>
        /// <returns>return string in UTC format: yyyyMMddHHmmss</returns>
        public static string NowToUTCString()
        {
            try
            {
                System.DateTime dtmThisMoment = System.DateTime.Now;
                string strRet = dtmThisMoment.ToString(UTC_STRING_FORMAT);
                return strRet;
            }
            catch
            {
                return string.Empty;
            }
        }

        /// <summary>		
        /// Thachnn: 24/Sep/2005
        /// Convert input DateTime object to UTC string. Format = yyyyMMddHHmmss
        /// Ex: 20050916590000
        /// </summary>
        /// <param name="pdmtDateTime">DateTime object to convert</param>
        /// <returns>return string in UTC format: yyyyMMddHHmmss</returns>		
        public static string DateTimeToUTCString(DateTime pdmtDateTime)
        {
            try
            {
                string strRet = pdmtDateTime.ToString(UTC_STRING_FORMAT);
                return strRet;
            }
            catch
            {
                return string.Empty;
            }
        }

		public static string DateTimeToShortUTCString(DateTime pdmtDateTime)
		{
			try
			{
				string strRet = pdmtDateTime.ToString(UTC_STRING_FORMAT).Substring(0,8);
				return strRet;
			}
			catch
			{
				return string.Empty;
			}
		}
		
		/// <summary>	
        /// Thachnn: 24/Sep/2005	
        /// Convert input UTC string (Format = yyyyMMddHHmmss) to DateTime object						
        /// </summary>
        /// <param name="strUTC">UTC string in yyyyMMddHHmmss format</param>
        /// <returns>result DateTime object</returns>
        public static System.DateTime UTCStringToDateTime(string strUTC)
        {
            try
            {
                System.DateTime oRet = new System.DateTime(
                    int.Parse(strUTC.Substring(0, 4)),	// year
                    int.Parse(strUTC.Substring(4, 2)),	// month
                    int.Parse(strUTC.Substring(6, 2)),	// day
                    int.Parse(strUTC.Substring(8, 2)),	// hour
                    int.Parse(strUTC.Substring(10, 2)),	// minute
                    int.Parse(strUTC.Substring(12, 2))		// second				
                    );
                return oRet;
            }
            catch
            {
                return DateTime.MinValue;
            }
        }


        #endregion







        ////////////   below is obsolete /////////
        //////////////////   ||    ///////////////
        //////////////////   ||    ///////////////
        //////////////////   ||    ///////////////
        //////////////////   ||    ///////////////
        //////////////////   \/    ///////////////

        const int DEFAULT_WIDTH = 1;
        const int THREE_FISRT_CHAR = 3;
        const int DECIMAL_ROUND = 2;
        
        #region Thachnn Kill Injection

        /// <summary>
        /// Thachnn: 01/Oct/2005
        /// Example:
        /// Init the mapping:
        /// map.Add("'","''");
        /// map.Add("-","--");
        /// Call function:
        /// inject = KillInjection(map,inject);
        /// pMap can be null or does not have value. In this case, we kill the ' character by default
        /// </summary>
        /// <param name="pnvarrMappingTable">mapping table to replace old value with new value</param>
        /// <param name="strInject">injected string to kill</param>
        /// <returns>free injection string. If error, return string.Empty</returns>
        public static string KillInjection(System.Collections.Specialized.NameValueCollection pnvarrMappingTable, string strInject)
        {
            System.Collections.Specialized.NameValueCollection nvarrMappingTable = pnvarrMappingTable;

            if (null == nvarrMappingTable || nvarrMappingTable.Count <= 0)	// pnvarrMappingTable is not define, then we kill the default ' character
            {
                /// DEFAULT KILL INJECTION
                nvarrMappingTable = new System.Collections.Specialized.NameValueCollection();
                nvarrMappingTable.Add("'", "''");
            }
            if (strInject != null)
            {
                foreach (string strOld in nvarrMappingTable.AllKeys)
                {
                    try
                    {
                        strInject = strInject.Replace(strOld, nvarrMappingTable.Get(strOld));
                    }
                    catch
                    {
                        return string.Empty;
                    }
                }
            }
            return strInject;
        }


        /// <summary>
        /// Thachnn: 30/Sep/2005
        /// OVERLOAD INTERFACE
        /// </summary>		
        /// <param name="strInject">injected string to kill</param>
        /// <returns>free injection string. If error, return string.Empty</returns>
        public static string KillInjection(string strInject)
        {
            return KillInjection(null, strInject);
        }


        /// <summary>
        /// Thachnn: 04/Oct/2005
        /// When SQL clause contain one LIKE pair (aa like VALUE)
        /// this function analyze the SQL clause, find the LIKE pair and KillInjection in VALUE
        /// </summary>
        /// <param name="pstrSQL">SQL clause with LIKE pair (aa like Value)</param>
        /// <returns>if SUCCESS: return SQL sentence with clean LIKE Clause, return null if error</returns>
        public static string KillInjectionInLikeClause(string pstrSQL)
        {
            string strRet = null;
            string strLikeClause = null;
            string strLikeValue = null;

            /// ignore case sensitive
            string strRegexp = @"(?<likeGR>(like|LIKE)(\s*)')(?<contentGR>.*)(?<endGR>(\s*)(%(\s*)'))";

            try
            {
                Match oMatch = Regex.Match(pstrSQL, strRegexp, RegexOptions.IgnoreCase);
                if (oMatch.Success)
                {
                    strLikeClause = oMatch.Value;	// get like string from LIKE '   till     %'
                }
                if (strLikeClause != null)
                {
                    strLikeValue = Regex.Replace(strLikeClause, strRegexp, @"${contentGR}", RegexOptions.IgnoreCase);	// extract the Like Value
                }
                if (strLikeValue != null)
                {
                    strLikeValue = KillInjection(null, strLikeValue);	// Kill injection in strLikeValue
                }

                strRet = Regex.Replace(pstrSQL, strRegexp, @"LIKE N'" + strLikeValue + "%'", RegexOptions.IgnoreCase);	// Put the pure LikeValue into the original SQL Like Query
            }
            catch
            {
                strRet = null;
            }
            return strRet;
        }


        #endregion

        #region Thachnn Replace Param with VALUE in string

        /// <summary>
        /// Thachnn: 06 Oct 2005
        /// Find in the SQL clause		
        /// Replace SQL parameter (named pstrPara) with its value (named pstrValue)
        /// if pstr value is string.Empty or null then I remove the whole parameter (remove pattern: a=@a)
        /// if I can't find the pattern a=@a or something like that, I return the original SQL clause
        /// THROW: Exception if error
        /// </summary>
        /// <history>
        /// Thachnn: 20/10/2005: make this function can work with [TableName].[FieldName] syntax style
        /// </history>		
        /// <param name="pstrSQL">input SQL clause</param>
        /// <param name="pstrPara">parameter name (like @something)</param>
        /// <param name="pstrValue">parameter value, can be null or string.Empty</param>
        /// <param name="pblnIsMultiSelection">True: Parameter allows user to select mutil rows</param>
        /// <returns>result SQL clause, if I can't find the pattern a=@a or something like that, I return the original SQL clause</returns>
        public static string FindAndReplaceParameterRegEx(string pstrSQL, string pstrPara, string pstrValue, bool pblnIsMultiSelection)
        {
            string METHOD_NAME = ".FindAndReplaceParameterRegEx()";
            try
            {
                string strPattern = string.Empty;
                string strReplacePattern = string.Empty;

                pstrSQL += "   ";	//refine the SQL clause, do not allow it end with "\n", fix bug when replace the last parameter
                string strRet = StardandizeSQL(pstrSQL);

                // We need to define pattern right upper the Match command to easy to debug.
                strPattern = @"(?<fieldGR>(\s*)((\[|)(\w*)(\]|)(\.|)(\[|)(\w*)(\]|))(\s*))"
                    + @"(?<operatorGR>((\s)in(\s))|((\s)like(\s))|=|>|<|>=|<=|<>)(\s*)"
                    + @"(?<valueGR>\(" + pstrPara + @"\)|" + pstrPara + @")(\s+)";
                //				strPattern = @"(?<fieldGR>(?<open>\[)?\w+(?(open)\])\.)?(?<open2>\[)?\w+(?(open2)\])\s*"
                //					+ @"(?<operatorGR>like|=|>|<|>=|<=|<>|(?<in>IN))\s*(?(in)\()"
                //					+ @"(?<valueGR>\s*?" + pstrPara + @"\s*?)(?(in)\))";
                Match oMatch = Regex.Match(pstrSQL, strPattern, RegexOptions.IgnoreCase);

                if (oMatch.Success)
                {
                    // if value is '' string (single quote, single quote) or null or empty, then we remove parameter from the sql command
                    if ((pstrValue == "''") || (pstrValue == string.Empty) || (null == pstrValue))
                    {
                        /// Kill non-last PARAM
                        //						strPattern = @"(?<fieldGR>(?<open>\[)?\w+(?(open)\])\.)?(?<open2>\[)?\w+(?(open2)\])\s*"
                        //							+ @"(?<operatorGR>like|=|>|<|>=|<=|<>|(?<in>IN))\s*(?(in)\()"
                        //							+ @"(?<valueGR>\s*?" + pstrPara + @"\s*?)(?(in)\))"
                        strPattern = @"(?<fieldGR>(\s*)((\[|)(\w*)(\]|)(\.|)(\[|)(\w*)(\]|))(\s*))"
                            + @"(?<operatorGR>((\s)in(\s))|((\s)like(\s))|=|>|<|>=|<=|<>)(\s*)"
                            + @"(?<valueGR>\(" + pstrPara + @"\)|" + pstrPara + @")(\s+)"
                            + @"(?<booloperatorGR>(and)|(or))";
                        strReplacePattern = " ";
                        strRet = Regex.Replace(pstrSQL, strPattern, strReplacePattern, RegexOptions.IgnoreCase);

                        if (strRet == pstrSQL)	// mean SQL clause is "SELECT * FROM XXX WHERE a = @a   . Kill param pair Not follow by AND,OR (the last PARAM)
                        {
                            //							strPattern = @"(?<fieldGR>(?<open>\[)?\w+(?(open)\])\.)?(?<open2>\[)?\w+(?(open2)\])\s*"
                            //								+ @"(?<operatorGR>like|=|>|<|>=|<=|<>|(?<in>IN))\s*(?(in)\()"
                            //								+ @"(?<valueGR>\s*?" + pstrPara + @"\s*?)(?(in)\))";
                            strPattern = @"(?<fieldGR>(\s*)((\[|)(\w*)(\]|)(\.|)(\[|)(\w*)(\]|))(\s*))"
                                + @"(?<operatorGR>((\s)in(\s))|((\s)like(\s))|=|>|<|>=|<=|<>)(\s*)"
                                + @"(?<valueGR>\(" + pstrPara + @"\)|" + pstrPara + @")(\s+)";
                            strReplacePattern = " ";
                            strRet = Regex.Replace(pstrSQL, strPattern, strReplacePattern, RegexOptions.IgnoreCase);
                        }
                    }
                    else // replace parameter by its value
                    {
                        //						strPattern = @"(?<fieldGR>(?<open>\[)?\w+(?(open)\])\.)?(?<open2>\[)?\w+(?(open2)\])\s*"
                        //							+ @"(?<operatorGR>like|=|>|<|>=|<=|<>|(?<in>IN))\s*(?(in)\()"
                        //							+ @"(?<valueGR>\s*?" + pstrPara + @"\s*?)(?(in)\))";
                        strPattern = @"(?<fieldGR>(\s*)((\[|)(\w*)(\]|)(\.|)(\[|)(\w*)(\]|))(\s*))"
                            + @"(?<operatorGR>((\s)in(\s))|((\s)like(\s))|=|>|<|>=|<=|<>)(\s*)"
                            + @"(?<valueGR>\(" + pstrPara + @"\)|" + pstrPara + @")(\s+)";
                        // multi selection will use IN as operator, we need to put ()
                        if (pblnIsMultiSelection)
                            pstrValue = "(" + pstrValue + ")";
                        strReplacePattern = @" ${fieldGR}${operatorGR} " + pstrValue + " ";
                        strRet = Regex.Replace(pstrSQL, strPattern, strReplacePattern, RegexOptions.IgnoreCase);
                    }
                }
                strRet = Kill_SQL_BooleanOperator_AtLast(strRet);
                strRet = Kill_SQL_WHERE_AtLast(strRet);
                return strRet;
            }
            catch (Exception ex)
            {
                throw new Exception(METHOD_NAME, ex);
            }
        }


        /// <summary>
        /// Thachnn: 06 Oct 2005
        /// Remove the AND, OR operator at the end of the input SQL clause
        /// </summary>
        /// <param name="pstrSQL">input string</param>
        /// <returns>string with no SQL boolean operator at last</returns>
        public static string Kill_SQL_BooleanOperator_AtLast(string pstrSQL)
        {
            string METHOD_NAME = ".Kill_SQL_BooleanOperator_AtLast()";
            try
            {
                string strPattern = string.Empty;
                string strReplacePattern = string.Empty;

                pstrSQL += "   ";	//refine the SQL clause, do not allow it end with "\n", fix bug when replace the last parameter
                string strRet = pstrSQL;

                strPattern = @"(\s+)(?<booloperatorGR>(and|or)(\s*)$)";
                Match oMatch = Regex.Match(pstrSQL, strPattern, RegexOptions.IgnoreCase);

                if (oMatch.Success)
                {
                    strPattern = @"(\s+)(?<booloperatorGR>(and|or)(\s*)$)";
                    strReplacePattern = " ";
                    strRet = Regex.Replace(pstrSQL, strPattern, strReplacePattern, RegexOptions.IgnoreCase);
                }
                return strRet;
            }
            catch (Exception ex)
            {
                throw new Exception(METHOD_NAME, ex);
            }
        }


        /// <summary>
        /// Thachnn: 06 Oct 2005
        /// Remove the WHERE keyword at the end of the input SQL clause		
        /// </summary>
        /// <param name="pstrSQL">input string</param>
        /// <returns>string with no WHERE keyword at last</returns>
        public static string Kill_SQL_WHERE_AtLast(string pstrSQL)
        {
            string METHOD_NAME = ".Kill_SQL_WHERE_AtLast()";
            try
            {
                string strPattern = string.Empty;
                string strReplacePattern = string.Empty;

                pstrSQL += "   ";	//refine the SQL clause, do not allow it end with "\n", fix bug when replace the last parameter
                string strRet = pstrSQL;

                strPattern = @"(\s+)(?<booloperatorGR>(where)(\s*)$)";
                Match oMatch = Regex.Match(pstrSQL, strPattern, RegexOptions.IgnoreCase);

                if (oMatch.Success)
                {
                    strPattern = @"(\s+)(?<booloperatorGR>(where)(\s*)$)";
                    strReplacePattern = " ";
                    strRet = Regex.Replace(pstrSQL, strPattern, strReplacePattern, RegexOptions.IgnoreCase);
                }
                return strRet;
            }
            catch (Exception ex)
            {
                throw new Exception(METHOD_NAME, ex);
            }
        }


        /// <summary>
        /// Thachnn: 06 Oct 2005		
        /// replace all \n \t \r in the SQL clause to _space_ character
        /// </summary>
        /// <param name="pstrOld"></param>
        /// <returns>standard string</returns>
        public static string StardandizeSQL(string pstrOld)
        {
            string METHOD_NAME = ".StardandizeSQL()";
            try
            {
                string strRet = pstrOld;
                strRet = strRet.Replace("\t", " ");
                strRet = strRet.Replace("\n", " ");
                strRet = strRet.Replace("\r", " ");
                strRet = strRet.Replace(@"\t", " ");
                strRet = strRet.Replace(@"\n", " ");
                strRet = strRet.Replace(@"\r", " ");
                return strRet;
            }
            catch (Exception ex)
            {
                throw new Exception(METHOD_NAME, ex);
            }
        }


        #endregion
             	
    }
}
